<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Service\DataReturnService as DRS;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;

class ApiController extends Controller
{
    /**
     * @Author:  刘家腾
     * @DateTime 2019-04-17
     * @param    Request
     * @return   [type]
     */
    public function login(Request $request)
    {
        $postData  = $request->post();
        $validator = Validator::make($postData,
            [
                'username' => 'required|string',
                'password' => 'required|string',
            ]);
        if ($validator->fails()) {
             return DRS::returnErr('err','10001',$validator->errors());
        }
        $wheData['username'] = $postData['username'];
        $wheData['password'] = substr(Md5($postData['password']),0,-4); //md5($postData['password']);
        /**开发版  password 不加密*/
        $list = DB::table('admin')->where($wheData)->first();
        if (empty($list)) {
            
            return DRS::returnErr('err',10001,'账号密码不正确或账号不存在');
            die;
        }
       
        $listarr = json_decode(json_encode($list),true);
        $listarr['token'] = substr(Md5($listarr['id']),0,-12).date("YmdHis");

        Cache::put($listarr['token'], $listarr,28800); // 1 分钟
        return DRS::returnOk($listarr);
    }
    public function register(Request $request){
        $postData  = $request->post();
        $validator = Validator::make($postData,
            [
                'username' => 'required',
                'nicakname' => 'required',
                'mobile' => 'required',
                'password' => 'required',
            ]);
        if ($validator->fails()) {
            return DRS::returnErr('err','10001',$validator->errors());
        }
        if ( !empty($postData['email']) ) {
            $insData['email'] = $postData['email'];
        }
        $insData['username'] = $postData['username'];
        $insData['nicakname'] = $postData['nicakname'];
        $insData['mobile'] = $postData['mobile'];
        $insData['password'] = substr(Md5($postData['password']),0,-4);//$postData['password'];
        $insData['create_time'] = date("Y-m-d H:i:s");
        $insData['status'] = 1;
        $resID = DB::table('admin')->insertGetId($insData);

        if ($resID) {
            return DRS::returnOk($resID);
        }
        return DRS::returnErr('err','10001','注册失败');
    }

}
